<template>
  <page-meta :root-font-size="rootFontSize() + 'px'"></page-meta>

  <view class="page-container">
    <customHeader :title="headerTitle" />

    <view class="page-content" :style="{ top: height }">
      <view class="overall-container">
        <view class="overall-score">{{ pageData?.last_score }}</view>
        <text class="overall-desc">总体得分</text>
        <view class="overall-wrapper">
          <view class="wrapper-title">评测结果</view>
          <view class="wrapper-table">
            <view class="table-header">
              <text class="header">句序</text>
              <text class="header">得分</text>
              <text class="header">录音</text>
              <text class="header">详情</text>
            </view>
            <view class="table-row" v-for="(item, index) in pageData?.list" :key="index">
              <view class="col">
                <view class="index">{{ index + 1 }}</view>
              </view>
              <view class="col">
                <text class="score">{{ item.score }}</text>
              </view>
              <view class="col">
                <loudspeaker class="speaker" :voice="item.user_voice" />
              </view>
              <view class="col">
                <image class="detail" @click="handleToDetail(item)"
                  src="https://rwstatic.tentons.cn/web/Lesson/images/detail.png" />
              </view>
            </view>
          </view>
          <image class="wrapper-status" src="https://rwstatic.tentons.cn/web/Lesson/images/sentence-end-status.png" />
          <view class="wrapper-tag"></view>
        </view>
        <view class="overall-line"></view>

        <button class="overall-operate" @click="handleToNext">
          <template v-if="!isSynthesis">
            <template v-if="shareResult.isRelearn">
              <template v-if="isReStart">
                退出
              </template>
              <template v-else>
                重新开始
              </template>
            </template>
            <template v-else>
              <template v-if="currentCourse.next_lesson_data_id == -1">
                成绩报告
                <image class="video-button-right"
                  src="https://rwstatic.tentons.cn/web/Lesson/images/button-right-icon.png" />
              </template>
              <template v-else>
                继续学习
              </template>
            </template>
          </template>
          <template v-else>
            继续学习
          </template>
        </button>
      </view>
    </view>
  </view>

  <CwCommon />
</template>

<script setup lang="ts">
import { onLoad, onShow } from "@dcloudio/uni-app";
import { rootFontSize, util } from "@/utils/util";
import customHeader from "@/components/customHeader.vue";
import API from "@/api";
import { ref } from "vue";
import loudspeaker from "@/components/loudspeaker.vue";
import { startEvaluating } from "@/utils/chivox";
// @ts-ignore
import { ossDownLoad } from "@/utils/oss/oss.js";
import { getAnyApp } from "@/common/hooks";
import { requestSceneSpeakData } from "@/pages/lowPricedCourse/situationalDialog/sceneSpeak/index";
import { requestNecessaryData } from "@/pages/lowPricedCourse/rolePlaying/rolePlay/index";
import { handleNavigateTo } from "@/pages/lowPricedCourse/trialCourseHome/index";
import { useStore } from "vuex";

const store = useStore();
const { Cheese } = getAnyApp();

interface IResult {
  last_score: number;
  list: IVoice[];
}

interface IVoice {
  record_id: number;
  sentences: string;
  user_voice: string;
  score: number;
  analysis: {
    phoneme?: any[];
    [x: string]: any;
  };
  type: number;
  is_need_report: number;
}

interface ICourse {
  course_id: number;
  day_num: number;
  data_id: number;
  data_type: number;
  next_day_num: number,
  next_lesson_data_id: number;
  next_lesson_data_type: number;
  next_free_talk_id: number;
  next_speak_skill_id: number;
}

const fs = uni.getFileSystemManager();
const height = ref(getApp().globalData!.pageTop);

const sectionId = ref("");
const currentType = ref(0);
const listMap = ref(new Map());
const pageData = ref<IResult | null>(null);
const shareResult = ref<AnyObject>({
  isRelearn: false, // 是否重新开始
});
const headerTitle = ref("小结");

const isReStart = ref(false); // 是否再次重新开始
const isSynthesis = ref(true); // 是否是口语综合
const currentCourse = ref<ICourse>({
  course_id: 0,
  day_num: 0,
  data_id: 0,
  data_type: 0,
  next_day_num: 0,
  next_lesson_data_id: 0,
  next_lesson_data_type: 0,
  next_free_talk_id: 0,
  next_speak_skill_id: 0,
});

onLoad(async (option: any) => {
  if (option.headerTitle) {
    headerTitle.value = option.headerTitle;
  }
  sectionId.value = option.section_id;
  isReStart.value = option.isReStart === "true";
  if (option.isSynthesis) {
    isSynthesis.value = option.isSynthesis === "true";
  }
  currentType.value = Number(option.type) || Number(option.courseStep);

  if (option.data) {
    const result = JSON.parse(decodeURIComponent(option.data));
    if (!isSynthesis.value || isReStart.value) {
      shareResult.value = result;
    }
  }

  handleGetCurrentCourse();

  pageData.value = (await API.analysisData({ section_id: sectionId.value, type: currentType.value })) as IResult;

  pageData.value.list.forEach((item: IVoice) => {
    listMap.value.set(item.record_id, item);
  })
});

const handleGetCurrentCourse = () => {
  const temp = uni.getStorageSync("lowCourseMap");
  if (!temp) {
    return;
  }

  const courseMap = new Map(JSON.parse(temp));
  const course = courseMap.get(Number(store.state.currentDataId)) as any;
  currentCourse.value = course;

  console.log("course", course);
}

const handleToDetail = async (item: IVoice) => {
  let tempObj = {};
  const temp = uni.getStorageSync(`${item.record_id}`);

  if (temp) {
    tempObj = JSON.parse(temp);
  }
  const curItem = Object.assign(listMap.value.get(item.record_id), tempObj);

  if (curItem.is_need_report == 1) {
    // 数据修复
    util.showLoading();
    ossDownLoad(item.user_voice, false).then((oss: { data: any; }) => {
      fs.readFile({
        filePath: oss.data,
        success: (file) => {
          startEvaluating({
            evaluatingInfo: { sentence: item.sentences },
            audioBuffer: file.data as ArrayBuffer,
            onSuccess: (eva) => {
              API.repair({
                section_id: sectionId.value,
                type: item.type,
                record_id: item.record_id,
                analysis: JSON.stringify(eva),
                thirdParty: "chevon",
              }).then(async res => {
                const temp = Object.assign(curItem, res, { is_need_report: 0 });

                listMap.value.set(item.record_id, temp);
                util.hideLoading();

                uni.navigateTo({
                  url: `/pages/lowPricedCourse/situationalDialog/scoreResult/index?activeModal=scoreEvaluation&section_id=${sectionId.value}&data=${encodeURIComponent(JSON.stringify(temp))}`,
                });
              })
            },
            onError: (errMsg) => {
              console.log(errMsg);
              util.showDialogue(errMsg);
              util.hideLoading();
            },
          })
        },
        fail: (errMsg) => {
          console.log(errMsg);
          util.hideLoading();
          util.showDialogue("找不到音频文件");
        }
      })
    })
  } else {
    uni.navigateTo({
      url: `/pages/lowPricedCourse/situationalDialog/scoreResult/index?activeModal=scoreEvaluation&section_id=${sectionId.value}&data=${encodeURIComponent(JSON.stringify(curItem))}`,
    });
  }
}

const handleToNext = async () => {
  if (!isSynthesis.value) {
    if (shareResult.value.isRelearn) {
      if (isReStart.value) {
        uni.reLaunch({
          url: "/pages/lowPricedCourse/trialCourseHome/trialCourse/index",
        })
      } else {
        let result: any;
        let lessonPage = "";

        if (currentType.value === 3) {
          result = await requestNecessaryData(Number(sectionId.value));
          lessonPage = "/pages/lowPricedCourse/rolePlaying/rolePlay/index";
        } else if (currentType.value === 4) {
          result = await requestSceneSpeakData(Number(sectionId.value));
          lessonPage = "/pages/lowPricedCourse/situationalDialog/sceneSpeak/index";
        }

        uni.navigateTo({
          url: `${lessonPage}?section_id=${sectionId.value}&data=${encodeURIComponent(JSON.stringify(result))}&courseStep=${currentType.value}&isReStart=true&isSynthesis=${isSynthesis.value}`
        })
      }
    } else {
      if (currentCourse.value.next_lesson_data_id == -1) {
        const result = await API.shareDailyResult({
          day_num: currentCourse.value.next_day_num,
          course_id: currentCourse.value.course_id,
        });

        const temp = Object.assign(result, Cheese.User?.USERINFO, {
          day_num: currentCourse.value.next_day_num,
          course_id: currentCourse.value.course_id,
        });

        uni.navigateTo({
          url: `/pages/lowPricedCourse/situationalDialog/scoreReport/index?data=${encodeURIComponent(JSON.stringify(temp))}`,
        });
      } else {
        const params: any = {
          data_id: currentCourse.value.next_lesson_data_id,
          data_type: currentCourse.value.next_lesson_data_type,
          free_talk_id: currentCourse.value.next_free_talk_id,
          speak_skill_id: currentCourse.value.next_speak_skill_id,
          process: 0,
          isReLaunch: true,
        }

        await handleNavigateTo(params);
      }
    }
  } else {
    uni.reLaunch({
      url: `/pages/lowPricedCourse/trialCourseHome/transitionPage/index?courseStep=${currentType.value + 1}&lastCourseStep=${currentType.value}&section_id=${sectionId.value}`,
    });
  }
}
</script>

<style scoped lang="scss">
.page-content {
  .overall-container {
    width: 100%;
    height: 100%;
    overflow: auto;

    .overall-score {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 7.2rem;
      height: 7.2rem;
      margin: 3.5rem auto 1.4rem;
      font-size: 3rem;
      font-family: baloo;
      color: #ffffff;
      background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/score-wrapper.png");
      background-size: contain;
      background-repeat: no-repeat;
    }

    .overall-desc {
      display: block;
      margin-bottom: 3.1rem;
      text-align: center;
      font-size: 2rem;
      font-family: xiaolai;
      color: $uni-text-color;
    }

    .overall-wrapper {
      position: relative;
      width: 35rem;
      margin: 1.5rem auto;
      padding-top: 2rem;
      border-image-slice: 27 27 27 27 fill;
      border-image-width: 2rem 2rem 2rem 2rem;
      border-image-outset: 0 0 0 0;
      border-image-repeat: stretch stretch;
      border-style: solid;
      border-image-source: url("https://rwstatic.tentons.cn/web/Lesson/images/sentence-wrapper.png");

      .wrapper-title {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 7.5rem;
        height: 1.8rem;
        margin: 0 auto 1.8rem;
        font-family: xiaolai;
        font-size: 1.7rem;
        color: $uni-text-color;
        background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/sentence-text.png");
        background-size: contain;
        background-repeat: no-repeat;
      }

      .wrapper-table {
        padding: 0 3.2rem;
        margin-bottom: 2.8rem;

        .table-header {
          display: flex;
          justify-content: space-between;
          width: 100%;
          height: 3.4rem;
          border-bottom: 1px solid #faefde;

          .header {
            display: flex;
            justify-content: center;
            width: 4rem;
            line-height: 2.4rem;
            font-family: xiaolai;
            font-size: 1.4rem;
            color: $uni-text-color;
          }
        }

        .table-row {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          height: 2.7rem;
          margin-top: 1.1rem;
          margin-bottom: 1.6rem;

          .col {
            width: 4rem;
            display: flex;
            justify-content: center;

            .index {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 1.8rem;
              height: 1.8rem;
              border-radius: 50%;
              font-family: xiaolai;
              font-size: 1.4rem;
              color: $uni-text-color;
              background-color: #ffebca;
            }

            .score {
              font-family: baloo;
              font-size: 1.8rem;
              color: #bf893d;
            }

            .speaker {
              width: 3.1rem;
              height: 3.1rem;
            }

            .detail {
              width: 1.8rem;
              height: 1.8rem;
            }
          }
        }
      }

      .wrapper-status {
        display: flex;
        justify-content: center;
        width: 27.6rem;
        height: 1.6rem;
        margin: 1.2rem auto 2rem;
      }

      .wrapper-tag {
        position: absolute;
        width: 8.2rem;
        height: 8.2rem;
        top: -2.5rem;
        left: 6.5rem;
        background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/sentence-tag.png");
        background-size: contain;
        background-repeat: no-repeat;
      }
    }

    .overall-line {
      height: 10rem;
    }

    .overall-operate {
      position: absolute;
      bottom: 2.5rem;
      left: 3rem;
      right: 3rem;
      margin: 0;
      font-family: xiaolai;
      font-size: 1.7rem;
      border-radius: 1rem;
      color: $uni-text-color;
      border: 2px solid $uni-btn-border;
      background-color: $uni-btn-prime;

      .video-button-right {
        width: 1.2rem;
        height: 1.2rem;
      }
    }

    .is-hover {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}
</style>
